# -*- coding: utf-8 -*-
'''
Created on 28/ott/2009

@author: sax
'''
from django.core.urlresolvers import reverse
import logging
#
# Some useful functions to use in changelist field render
#
def _wrap_column(f, field_name, label=None, order=None):
    """ utility to add extra attributes to method that could be used as columns """
    f.short_description = label or field_name
    f.allow_tags = True
    f.admin_order_field = order
    f.label = label
    return f

def get_email_href(field_name, label=None, order=None): 
    def inner(self, obj):  #IGNORE:W0613
        try:
            value = getattr(obj, field_name)
        except AttributeError, e:
            logging.critical(e)  
            return ""
        if not value:
            return ""
        lbl = label or str(value)
        return "<a href='mailto:%s'>%s</a>" % (value, lbl)

    return _wrap_column(inner, field_name, label, order)


def get_model_change_href(field_name, label=None, order=None):
    def inner(self, obj):
        if obj is None:
            return ""
        
        try:
            model_instance = getattr(obj, field_name)
        except AttributeError, e:
            logging.critical(e)  
            return ""
              
        if model_instance is None:
            return ""
        
        ma = self.admin_site._registry[model_instance.__class__]
        name = "%s:%s" % (self.admin_site.name, ma.get_changeview_name())
        url =  reverse(name, args=[model_instance.pk])
        lbl = inner.label or str(model_instance)
        ret = '<a class="modellink" href="%s">%s</a>' % (url, lbl)
        return ret
        
    return _wrap_column(inner, field_name, label, order)


